logo头像
Snippet 博客主题

android Flutter 5.获取数据

本文于370天之前发表,文中内容可能已经过时。

移动端-Flutter-5.获取数据

1 添加http包
2 使用http 软件包发送网络请求
3 解析数据
4 显示 数据

1 添加http包

在pubspec.yaml中添加 http 包

1
2
dependencies:
http: <latest_version>

2 使用http 软件包发送网络请求

1
2
3
Future<http.Response> fetchPost() {
return http.get('https://jsonplaceholder.typicode.com/posts/1');
}

3 解析数据

创建解析对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return new Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}

解析数据

1
2
3
4
5
Future<Post> fetchPost() async {
final response = await http.get('https://jsonplaceholder.typicode.com/posts/1');
final responseJson = json.decode(response.body);
return new Post.fromJson(responseJson);
}

4 显示 数据

1
2
3
4
5
6
7
8
9
10
11
12
new FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.title);
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
// By default, show a loading spinner
return new CircularProgressIndicator();
},
);

code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
Future<Post> fetchPost() async {
final response =
await http.get('https://jsonplaceholder.typicode.com/posts/1');
final responseJson = json.decode(response.body);
return new Post.fromJson(responseJson);
}
class Post {
final int userId;
final int id;
final String title;
final String body;
Post({this.userId, this.id, this.title, this.body});
factory Post.fromJson(Map<String, dynamic> json) {
return new Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Fetch Data Example',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new Scaffold(
appBar: new AppBar(
title: new Text('Fetch Data Example'),
),
body: new Center(
child: new FutureBuilder<Post>(
future: fetchPost(),
builder: (context, snapshot) {
if (snapshot.hasData) {
return new Text(snapshot.data.title);
} else if (snapshot.hasError) {
return new Text("${snapshot.error}");
}
// By default, show a loading spinner
return new CircularProgressIndicator();
},
),
),
),
);
}
}

支付宝打赏 微信打赏

打赏